//
//  RTEmotionTools.swift
//  Weibo
//
//  Created by Brisinga on 16/3/14.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

let RTEmotionPageCount = 20

class RTEmotionTools: NSObject {

    
    // 单例
    static var sharedEmotionTools: RTEmotionTools = RTEmotionTools()
    
    
    private override init() {
        
    }
    
    
    // 表情数据的bundle
    private lazy var emotionBundle: NSBundle = {
        
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        
        let emotionBundle = NSBundle(path: path)!
        
        return emotionBundle
    }()
    
    
    
    // 最近表情
    lazy var recentEmotion: [RTEmotion] = {
        
        return [RTEmotion]()
    }()
    
    // 默认表情
    lazy var defaultEmotion: [RTEmotion] = {
        
        return self.emotionWithFolderName("default")
    }()
    
    // emoji
    lazy var emojiEmotion: [RTEmotion] = {
        
        return self.emotionWithFolderName("emoji")

    }()
    
    // 浪小花
    
    lazy var lxhEmotion: [RTEmotion] = {
    
        return self.emotionWithFolderName("lxh")

    }()
    
    
    // 所需要的表情数据
    lazy var allEmoticons: [[[RTEmotion]]] = {
        
        return [
        
            [self.recentEmotion],
            
            self.typeEmoticonPages(self.defaultEmotion),
            
            self.typeEmoticonPages(self.emojiEmotion),
            
            self.typeEmoticonPages(self.lxhEmotion),
        ]
    
    }()
    
    
    
    // 返回表情分成的二维数组
     private func typeEmoticonPages(emotions: [RTEmotion])->[[RTEmotion]] {
    
        // 计算出一共有几页
        let pages = (emotions.count - 1)/RTEmotionPageCount+1
        
        var result = [[RTEmotion]]()
        
        for i in 0..<pages {
            
            // 计算开始截取位置
            let location = i * RTEmotionPageCount
            
            // 截取长度
            var len = RTEmotionPageCount
            
            if location + len > emotions.count {
                
                len = emotions.count - location
            }
            
            let range = NSMakeRange(location, len)
            
            let subArr = (emotions as NSArray).subarrayWithRange(range) as! [RTEmotion]
            
            result.append(subArr)
        }
        
        return result
    
    }
    
    
    // 获取表情数组
     private func emotionWithFolderName(folderName: String) -> [RTEmotion] {
    
        let path = self.emotionBundle.pathForResource("\(folderName)/info.plist", ofType: nil)!
        
        let tempArr = NSArray(contentsOfFile: path)!
        
        var result = [RTEmotion]()
        
        for value in tempArr {
            
            let emotion = RTEmotion(dict: value as! [String : AnyObject])
            
            result.append(emotion)
            
        }
        
        return result
    }
}
